package br.com.sovi.gwt.client.component.mainmenu;

import com.google.gwt.user.client.History;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListener;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;

public class MainMenu extends Toolbar {

	public MainMenu() {
		String token = History.getToken();
		MainMenuOptionsEnum currentOption = MainMenuOptionsEnum.getByToken(token);

		if (currentOption == null) {
			currentOption = MainMenuOptionsEnum.INICIO;
		}

		MainMenuOptionsEnum[] values = MainMenuOptionsEnum.values();

		for (int i = 0; i < values.length; i++) {
			MainMenuOptionsEnum mainMenuOptionsEnum = values[i];

			boolean currentButton = (mainMenuOptionsEnum.equals(currentOption));

			this.addButton(createButton(mainMenuOptionsEnum.getLabel(), currentButton, new TokenChangeButtonListener(
					mainMenuOptionsEnum)));
			
			if (i < (values.length-1)) {
				this.addSeparator();
			}
		}
	}

	private class TokenChangeButtonListener extends ButtonListenerAdapter {

		private MainMenuOptionsEnum mmoe;

		private TokenChangeButtonListener(MainMenuOptionsEnum mmoe) {
			super();
			this.mmoe = mmoe;
		}

		@Override
		public void onToggle(Button button, boolean pressed) {
			if (pressed) {
				History.newItem(mmoe.getToken());
			}
		}

	}

	private ToolbarButton createButton(String text, boolean toggle, ButtonListener buttonListener) {
		ToolbarButton toolbarButton = new ToolbarButton(text);
		toolbarButton.setToggleGroup("menu");
		toolbarButton.setEnableToggle(true);
		toolbarButton.toggle(toggle);
		if (buttonListener != null) {
			toolbarButton.addListener(buttonListener);
		}
		return toolbarButton;
	}

}
